using System;
using System.Collections.Generic;
using Ioc.Kernel.Exceptions;
using Ioc.Kernel.LifeStyles;
using Ioc.Kernel.Resolvers;
using Ioc.Kernel.Selectors;

namespace Ioc.Kernel
{
    public class IocContainer : IIocContainer
    {
        private readonly IDictionary<ContainerKey, ComponentModel> components;
        private IResolver resolver;
        private IComponentSelector componentSelector;
        private IComponentChecker componentChecker;

        public IDictionary<ContainerKey, ComponentModel> Components
        {
            get { return components; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="IocContainer"/> class.
        /// </summary>
        public IocContainer()
        {
            components = new Dictionary<ContainerKey, ComponentModel>();
            resolver = null;
            componentSelector = null;
        }

        #region AddComponent

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        public void AddComponent(string name, Type className)
        {
            AddComponent(name, className, className);
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="lifecycle">The lifecycle.</param>
        public void AddComponent(string name, Type className, LifeStyleType lifecycle)
        {
            AddComponent(name, className, className, lifecycle);
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="lifecycle">The lifecycle.</param>
        /// <param name="componentExpectedLifeTime">The component expected life time.</param>
        public void AddComponent(string name, Type className, LifeStyleType lifecycle, int componentExpectedLifeTime)
        {
            AddComponent(name, className, className, lifecycle, componentExpectedLifeTime);
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="parameters">The parameters.</param>
        public void AddComponent(string name, Type className, IList<Parameter> parameters)
        {
            AddComponent(name, className, className, parameters);
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="lifecycle">The lifecycle.</param>
        /// <param name="parameters">The parameters.</param>
        public void AddComponent(string name, Type className, LifeStyleType lifecycle, IList<Parameter> parameters)
        {
            AddComponent(name, className, className, lifecycle, parameters);
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="lifecycle">The lifecycle.</param>
        /// <param name="componentExpectedLifeTime">The component expected life time.</param>
        /// <param name="parameters">The parameters.</param>
        public void AddComponent(string name, Type className, LifeStyleType lifecycle, int componentExpectedLifeTime, IList<Parameter> parameters)
        {
            AddComponent(name, className, className, lifecycle, componentExpectedLifeTime, parameters);
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="serviceName">Name of the service.</param>
        public void AddComponent(string name, Type className, Type serviceName)
        {
            AddComponent(new ComponentModel(name,className,serviceName), new List<Parameter>());
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="parameters">The parameters.</param>
        public void AddComponent(string name, Type className, Type serviceName, IList<Parameter> parameters)
        {
            AddComponent(new ComponentModel(name, className, serviceName), parameters);
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="lifecycle">The lifecycle.</param>
        public void AddComponent(string name, Type className, Type serviceName, LifeStyleType lifecycle)
        {
            AddComponent(new ComponentModel(name, className, serviceName, LifeStyleFactory.GetLifecycle(lifecycle, -1)),
                         new List<Parameter>());
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="lifecycle">The lifecycle.</param>
        /// <param name="componentExpectedLifeTime">The component expected life time.</param>
        public void AddComponent(string name, Type className, Type serviceName, LifeStyleType lifecycle, int componentExpectedLifeTime)
        {
            AddComponent(new ComponentModel(name, className, serviceName, LifeStyleFactory.GetLifecycle(lifecycle, componentExpectedLifeTime)),
                         new List<Parameter>());
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="lifecycle">The lifecycle.</param>
        /// <param name="parameters">The parameters.</param>
        public void AddComponent(string name, Type className, Type serviceName, LifeStyleType lifecycle,
                                 IList<Parameter> parameters)
        {
            AddComponent(new ComponentModel(name, className, serviceName, LifeStyleFactory.GetLifecycle(lifecycle, -1)),
                         parameters);
        }

        /// <summary>
        /// Adds the component.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="lifecycle">The lifecycle.</param>
        /// <param name="componentExpectedLifeTime">The component expected life time.</param>
        /// <param name="parameters">The parameters.</param>
        public void AddComponent(string name, Type className, Type serviceName, LifeStyleType lifecycle, int componentExpectedLifeTime, IList<Parameter> parameters)
        {
            AddComponent(new ComponentModel(name, className, serviceName, LifeStyleFactory.GetLifecycle(lifecycle, componentExpectedLifeTime)),
                         parameters);
        }

        /// <summary>
        /// Adds the specified component.
        /// </summary>
        /// <param name="component">The component.</param>
        /// <param name="parameters">The parameters.</param>
        private void AddComponent(ComponentModel component, IList<Parameter> parameters)
        {
            if (componentChecker == null)
                componentChecker = new ComponentChecker(components);
            componentChecker.CheckComponent(component);

            // Adding the parameters
            foreach (var parameter in parameters)
            {
                component.AddParameters(parameter);
            }

            components.Add(new ContainerKey(component.Name, component.ServiceName), component);
        }

        #endregion

        /// <summary>
        /// Resolves this instance.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Resolve<T>()
        {
            InitializeComponentSelector();
            return (T)ResolveComponent(componentSelector.GetComponent(typeof(T), string.Empty));
        }

        /// <summary>
        /// Resolves this instance.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="componentName">Name of the component.</param>
        /// <returns></returns>
        public T Resolve<T>(string componentName)
        {
            InitializeComponentSelector();
            return (T)ResolveComponent(componentSelector.GetComponent(typeof(T), componentName));
        }

        /// <summary>
        /// Initializes the component selector.
        /// </summary>
        private void InitializeComponentSelector()
        {
            if (componentSelector == null)
                componentSelector = new ComponentSelector(components);
        }

        /// <summary>
        /// Resolves the component.
        /// </summary>
        /// <param name="componentKey">The component key.</param>
        /// <returns></returns>
        private object ResolveComponent(ContainerKey componentKey)
        {
            if (resolver == null)
                resolver = new Resolver(components);

            return resolver.Instanciate(components[componentKey]);
        }

        /// <summary>
        /// Removes the component.
        /// </summary>
        /// <param name="componenteId">The componente id.</param>
        public void RemoveComponent(string componenteId)
        {
            ContainerKey ComponentToRemove = null;
            foreach (var containerComponent in components.Keys)
            {
                if (containerComponent.ComponentName == componenteId)
                {
                    ComponentToRemove = containerComponent;
                    break;
                }
            }
            if (ComponentToRemove == null)
                throw new RemoveUnexistingComponentException(componenteId);

            components[ComponentToRemove].Dispose();
            components.Remove(ComponentToRemove);
        }

        /// <summary>
        /// Removes all components.
        /// </summary>
        public void RemoveAllComponents()
        {
            foreach (var component in components.Values)
            {
                component.Dispose();
            }
            components.Clear();
        }

        #region Disposing

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected void Dispose(bool disposing)
        {
            if(!disposing) return;
            
            RemoveAllComponents();
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="IocContainer"/> is reclaimed by garbage collection.
        /// </summary>
        ~IocContainer()
        {
            Dispose(false);
        }

        #endregion
    }
}